package com.yykj.tencent.im.server.utils;

import org.apache.commons.codec.binary.Base64;
import org.apache.commons.codec.binary.Hex;
import org.apache.pulsar.shade.org.eclipse.util.StringUtil;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.io.UnsupportedEncodingException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * 腾讯 移动推送 TPNS 获取sign
 */
public class SignUtil {

    public static String getSign(long timeStamp,String bodyJson, String AccessId, String secretKey) {
        try {
            //通过请求时间戳 + AccessId + 请求 body 进行字符拼接，得到原始的待签名字符串：
            //待签名字符串 = ${TimeStamp} + ${AccessId} + ${请求body}
            //通过 SecretKey 作为密钥，对原始待签名字符串进行签名，生成得到签名：
            //Sign = Base64(HMAC_SHA256(SecretKey, 待签名字符串))
            String stringToSign = timeStamp + AccessId + bodyJson;
            Mac mac = Mac.getInstance("HmacSHA256");
            mac.init(new SecretKeySpec(secretKey.getBytes("UTF-8"), "HmacSHA256"));
            byte[] signatureBytes = mac.doFinal(stringToSign.getBytes("UTF-8"));
            String hexStr = Hex.encodeHexString(signatureBytes);
            return Base64.encodeBase64String(hexStr.getBytes());
        } catch (NoSuchAlgorithmException | InvalidKeyException | UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static int date2TimeStamp(String strDate, String format) {
        if (StringUtil.isBlank(strDate)) {
            return 0;
        }
        int res = 0;
        SimpleDateFormat sdf = new SimpleDateFormat(format);
        Date date;
        try {
            date = sdf.parse(strDate);
            long ts = date.getTime() / 1000;
            res = Integer.parseInt(String.valueOf(ts));
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return res;
    }
}
